//
//  ForgetPswViewController.m
//  JiFengDaRen
//
//  Created by guest on 16/1/17.
//  Copyright © 2016年 SH_iOS. All rights reserved.
//
#import "UIButton+WebCache.h"
#import "ForgetPswViewController.h"
#import "JCLoginViewModel.h"

@interface ForgetPswViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) UIView      *firstBgView;
@property (nonatomic,strong) UIView      *secondBgView;
@property (nonatomic,strong) UIView      *thirdBgView;
@property (nonatomic,strong) UIView      *fouthBgView;

@property (nonatomic,strong) UIView      *verifyImgBgView;
@property (nonatomic,strong) UILabel      *verifyImgLabel;
@property (nonatomic,strong) UITextField  *verifyImgTf;
@property (nonatomic,strong) UIButton     *verifyImgBtn;



@property (nonatomic,strong) UILabel     *userNameLabel;
@property (nonatomic,strong) UILabel     *verificationCodeLabel;
@property (nonatomic,strong) UILabel     *passwordLabel;
@property (nonatomic,strong) UILabel     *confirmPasswordLabel;
@property (nonatomic,strong) UITextField *userNameTf;
@property (nonatomic,strong) UITextField *passwordTf;
@property (nonatomic,strong) UITextField *confirmPasswordTf;

@property (nonatomic,strong) UITextField *verificationCodeTf;
@property (nonatomic,strong) UIButton    *verificationCodeBtn;
@property (nonatomic,strong) UIButton    *modifyBtn;
@property (nonatomic,strong) NSTimer     *mytimer;
@property (nonatomic,strong) NSString     *url;
@property (nonatomic,strong) NSString     *id;


@property (nonatomic, strong) UIImageView *navigationBar;

@end

@implementation ForgetPswViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F7F8FA"];
    
    [self getVerifyImgCode];
    [self createNavigationBar];
    [self configUI];
    [self layoutUI];
}

- (void)createNavigationBar{
   
    self.navigationBar  = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KNAVIGATIONBARHEIGHT)];
    self.navigationBar.userInteractionEnabled = YES;
    self.navigationBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.navigationBar];
    
    UILabel *tilte = [[UILabel alloc]init];
    tilte.text = @"修改登录密码";
    tilte.textAlignment = NSTextAlignmentCenter;
    tilte.textColor = KSHTEXTCOLOR;
    tilte.font = KSystemFont(__I6Width(18));
    [self.navigationBar addSubview:tilte];
    [tilte mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).with.offset(KSTATUBARHEIGHT);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(__I6Width(200));
    }];
    
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [back setTintColor:[UIColor blackColor]];
    [back setImageEdgeInsets:UIEdgeInsetsMake(0,__I6Width(10), 0,__I6Width(50))];
    [back addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBar addSubview:back];
    
    [back mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBar.mas_left).with.offset(0);
        make.top.equalTo(self.view.mas_top).with.offset(KSTATUBARHEIGHT);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(__I6Width(80));
        
    }];
    
}


#pragma mark -- UI布局
- (void)configUI{
    self.firstBgView = [[UIView alloc]init];
    self.firstBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.firstBgView];

    self.secondBgView = [[UIView alloc]init];
    self.secondBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.secondBgView];

    self.thirdBgView = [[UIView alloc]init];
    self.thirdBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.thirdBgView];

    self.fouthBgView = [[UIView alloc]init];
    self.fouthBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.fouthBgView];

    self.verifyImgBgView = [[UIView alloc]init];
    self.verifyImgBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.verifyImgBgView];


    self.userNameLabel = [[UILabel alloc]init];
    self.userNameLabel.text = @"手机号码";
    self.userNameLabel.textColor = KSHTEXTCOLOR;
    self.userNameLabel.font = KSystemFont(14);
    [self.firstBgView addSubview:self.userNameLabel];

    self.verifyImgLabel = [[UILabel alloc]init];
    self.verifyImgLabel.text = @"图形码";
    self.verifyImgLabel.textColor = KSHTEXTCOLOR;
    self.verifyImgLabel.font = KSystemFont(14);
    [self.verifyImgBgView addSubview:self.verifyImgLabel];
    
    self.verificationCodeLabel = [[UILabel alloc]init];
    self.verificationCodeLabel.text = @"验证码";
    self.verificationCodeLabel.textColor = KSHTEXTCOLOR;
    self.verificationCodeLabel.font = KSystemFont(14);
    [self.secondBgView addSubview:self.verificationCodeLabel];

    self.passwordLabel = [[UILabel alloc]init];
    self.passwordLabel.text = @"新密码";
    self.passwordLabel.textColor = KSHTEXTCOLOR;
    self.passwordLabel.font = KSystemFont(14);
    [self.thirdBgView addSubview:self.passwordLabel];

    self.confirmPasswordLabel = [[UILabel alloc]init];
    self.confirmPasswordLabel.text = @"确认密码";
    self.confirmPasswordLabel.textColor = KSHTEXTCOLOR;
    self.confirmPasswordLabel.font = KSystemFont(14);
    [self.fouthBgView addSubview:self.confirmPasswordLabel];

    //文本框
    self.userNameTf = [[UITextField alloc]init];
    self.userNameTf.placeholder = @"中国大陆手机号";
    self.userNameTf.delegate = self;
    [self.userNameTf setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.userNameTf setValue:KSystemFont(14) forKeyPath:@"_placeholderLabel.font"];
    self.userNameTf.font = KSystemFont(14);
    self.userNameTf.textColor = KSHTEXTCOLOR;
    self.userNameTf.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview: self.userNameTf ];

    //文本框
    self.verifyImgTf = [[UITextField alloc]init];
    self.verifyImgTf.placeholder = @"请输入正确的图形码";
    self.verifyImgTf.delegate = self;
    [self.verifyImgTf setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.verifyImgTf setValue:KSystemFont(14) forKeyPath:@"_placeholderLabel.font"];
    self.verifyImgTf.font = KSystemFont(14);
    self.verifyImgTf.textColor = KSHTEXTCOLOR;
    self.verifyImgTf.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview: self.verifyImgTf ];

    self.verificationCodeTf = [[UITextField alloc]init];
    self.verificationCodeTf.placeholder = @"请输入验证码";
    self.verificationCodeTf.delegate = self;
    [self.verificationCodeTf setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.verificationCodeTf setValue:KSystemFont(14) forKeyPath:@"_placeholderLabel.font"];
    self.verificationCodeTf.font = KSystemFont(14);
    self.verificationCodeTf.textColor = KSHTEXTCOLOR;
    self.verificationCodeTf.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview: self.verificationCodeTf];

    self.passwordTf = [[UITextField alloc]init];
    self.passwordTf.delegate = self;
    self.passwordTf.placeholder = @"请输入您新的登录密码";
    self.passwordTf.secureTextEntry = YES;
    self.passwordTf.font = KSystemFont(14);
    self.passwordTf.textColor = KSHTEXTCOLOR;
    [self.passwordTf setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordTf setValue:KSystemFont(14) forKeyPath:@"_placeholderLabel.font"];
    self.passwordTf.clearButtonMode = UITextFieldViewModeAlways;
    [self.thirdBgView addSubview:self.passwordTf ];

    self.confirmPasswordTf = [[UITextField alloc]init];
    self.confirmPasswordTf.delegate = self;
    self.confirmPasswordTf.placeholder = @"请再次输入您新的登录密码";
    self.confirmPasswordTf.secureTextEntry = YES;
    self.confirmPasswordTf.font = KSystemFont(14);
    self.confirmPasswordTf.textColor = KSHTEXTCOLOR;
    [self.confirmPasswordTf setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.confirmPasswordTf setValue:KSystemFont(14) forKeyPath:@"_placeholderLabel.font"];
    self.confirmPasswordTf.clearButtonMode = UITextFieldViewModeAlways;
    [self.fouthBgView addSubview:self.confirmPasswordTf ];

    self.verificationCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.verificationCodeBtn.titleLabel.font = KSystemFont(14);
    [self.verificationCodeBtn setTitleColor:[UIColor colorWithHexString:@"#C28C42"] forState:UIControlStateNormal];
    [self.verificationCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];

     [self.verificationCodeBtn addTarget:self action:@selector(getYzm) forControlEvents:UIControlEventTouchUpInside];
    [self.secondBgView addSubview:self.verificationCodeBtn];

    self.verifyImgBtn = [[UIButton  alloc]init];
    [self.verifyImgBtn sd_setImageWithURL:[NSURL URLWithString:self.url] forState:UIControlStateNormal];
    [self.verifyImgBtn addTarget:self action:@selector(refreshVerifyImg:) forControlEvents:UIControlEventTouchUpInside];
    [self.verifyImgBgView addSubview:self.verifyImgBtn];


    self.modifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.modifyBtn setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];
    self.modifyBtn.titleLabel.font = KSystemFont(16);
    [self.modifyBtn setTitleColor:KSHTEXTCOLOR forState:UIControlStateNormal];
    [self.modifyBtn setTitle:@"立即修改" forState:UIControlStateNormal];
    [self.modifyBtn addTarget:self action:@selector(modifyId:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.modifyBtn];

    self.firstBgView.layer.borderWidth = 0.5;
    self.firstBgView.layer.borderColor = KLINECOLOR.CGColor;
    self.secondBgView.layer.borderWidth = 0.5;
    self.secondBgView.layer.borderColor = KLINECOLOR.CGColor;

    self.thirdBgView.layer.borderWidth = 0.5;
    self.thirdBgView.layer.borderColor = KLINECOLOR.CGColor;
    self.fouthBgView.layer.borderWidth = 0.5;
    self.fouthBgView.layer.borderColor = KLINECOLOR.CGColor;
    self.verifyImgBgView.layer.borderWidth = 0.5;
    self.verifyImgBgView.layer.borderColor = KLINECOLOR.CGColor;

}
#pragma mark --- 设置控件位置
-(void)layoutUI{
    //设置约束
    [self.firstBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(10 + KNAVIGATIONBARHEIGHT);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(__I6Height(50));
    }];

    [self.verifyImgBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.firstBgView.mas_bottom).offset(10);
        make.left.right.height.equalTo(self.firstBgView);
    }];

    [self.secondBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.verifyImgBgView.mas_bottom).offset(10);
        make.left.right.height.equalTo(self.firstBgView);
    }];

    [self.thirdBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.secondBgView.mas_bottom).offset(10);
        make.left.right.height.equalTo(self.firstBgView);
    }];

    [self.fouthBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.thirdBgView.mas_bottom).offset(10);
        make.left.right.height.equalTo(self.firstBgView);
    }];
    
    
    [self.userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.firstBgView);
        make.left.equalTo(self.firstBgView).offset(__I6Width(15));
        make.width.mas_offset(__I6Width(70));
    }];
    
    [self.userNameTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.equalTo(self.firstBgView);
        make.left.equalTo(self.userNameLabel.mas_right);
    }];

    [self.verifyImgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.verifyImgBgView);
        make.left.equalTo(self.verifyImgBgView).offset(__I6Width(15));
        make.width.mas_offset(__I6Width(70));
    }];
    
    [self.verifyImgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.centerY.equalTo(self.verifyImgBgView);
        make.width.mas_equalTo(__I6Width(110));
    }];
    
    [self.verifyImgTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.verifyImgBgView);
        make.left.equalTo(self.verifyImgLabel.mas_right).priority(700);
        make.right.equalTo(self.verifyImgBtn.mas_left).offset(-5).priority(200);
    }];

    [self.verificationCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.secondBgView);
        make.left.equalTo(self.secondBgView).offset(__I6Width(15));
        make.width.mas_offset(__I6Width(70));
    }];
    
    [self.verificationCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.equalTo(self.secondBgView);
        make.width.mas_offset(__I6Width(110));
    }];
    
    [self.verificationCodeTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.secondBgView);
        make.left.equalTo(self.verificationCodeLabel.mas_right);
        make.right.equalTo(self.verificationCodeBtn.mas_left).offset(-5);
    }];

    [self.passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.thirdBgView);
        make.left.equalTo(self.thirdBgView).offset(__I6Width(15));
        make.width.mas_offset(__I6Width(70));
    }];
    
    
    [self.passwordTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.equalTo(self.thirdBgView);
        make.left.equalTo(self.passwordLabel.mas_right);
    }];
    
    [self.confirmPasswordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.fouthBgView);
        make.left.equalTo(self.fouthBgView).offset(__I6Width(15));
        make.width.mas_offset(__I6Width(70));
    }];

    [self.confirmPasswordTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.equalTo(self.fouthBgView);
        make.left.equalTo(self.confirmPasswordLabel.mas_right);
    }];

    [self.modifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.fouthBgView.mas_bottom).offset(__I6Height(50));
        make.centerX.mas_equalTo(self.view);
    }];

 
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor colorWithHexString:@"#e6e6e6"];
    [self.secondBgView addSubview:line];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.secondBgView);
        make.right.equalTo(self.verificationCodeBtn.mas_left);
        make.width.mas_offset(.5);
        make.height.mas_offset(33);
    }];
    
    
    

}

#pragma mark --- 点击事件
- (void)getYzm{

    [self.view endEditing:YES];
    if (self.userNameTf.text.length == 0) {
        [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
        return;
    }

    if (![Tool isMobileNumber:self.userNameTf.text]) {
        [self.view makeToast:@"手机号格式不正确" duration:1 position:@"center"];
        return;
    }

    if (self.verifyImgTf.text.length == 0) {
        [self.view makeToast:@"请输入图形码" duration:1 position:@"center"];
        [self getVerifyImgCode];
        return;
    }
    
    if ( self.userNameTf.text.length != 0){
        
        [self startTime];
        [self sendVerifyImgCode];
            
    }else if(self.userNameTf.text.length == 0){
        
        [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
    }

}
- (void)startTime{
    
    __block int timeout = 30;//倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.verificationCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                self.verificationCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.verificationCodeBtn setTitle:[NSString stringWithFormat:@"%@S",strTime] forState:UIControlStateNormal];
                self.verificationCodeBtn.userInteractionEnabled = NO;

            });
            timeout--;

        }
    });
    dispatch_resume(_timer);

}


- (void)modifyId:(UIButton *)sender {
    [self.view endEditing:YES];
    if (self.userNameTf.text.length == 0) {
        [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
        return;
    }

    if (self.verificationCodeTf.text.length == 0) {
        [self.view makeToast:@"请输入验证码" duration:1 position:@"center"];
        return;
    }
    if (self.passwordTf.text.length == 0) {
        [self.view makeToast:@"请设置密码" duration:1 position:@"center"];
        return;
    }
    if ( self.passwordTf.text.length < 6 || self.passwordTf.text.length > 18) {
        [self.view makeToast:@"请输入6—18位密码" duration:1 position:@"center"];
        return;
    }
    if (self.confirmPasswordTf.text.length == 0) {
        [self.view makeToast:@"请再次输入密码" duration:1 position:@"center"];
        return;
    }

    if (![self.passwordTf.text isEqualToString:self.confirmPasswordTf.text]) {
        [self.view makeToast:@"两次输入的密码不一致！" duration:1 position:@"center"];
        return;
    }
    
    [self userForgetPsw];

    [super didReceiveMemoryWarning];
}

#pragma mark - 网络请求
// 获取图形验证吗
- (void)getVerifyImgCode{
    
    [JCLoginViewModel getVerifyImgCodeSuccess:^(NSDictionary *result) {
        
        self.url = result[@"data"][@"url"];
        self.id = result[@"data"][@"id"];
        [self.verifyImgBtn sd_setImageWithURL:[NSURL URLWithString:self.url] forState:UIControlStateNormal];
    }];
}

// 发送图形验证码
- (void)sendVerifyImgCode{
    
    NSDictionary *dict = @{@"phone":self.userNameTf.text,@"id":self.id,@"user_code":self.verifyImgTf.text};
    
    [JCLoginViewModel sendImgCodeParams:dict Success:^(NSDictionary *dict) {
        
        if ([dict[@"success"] boolValue] == YES) {
            [self.view makeToast:@"验证码发送成功!" duration:1 position:@"center"];
        }else{
            [self.view makeToast:dict[@"data"] duration:1 position:@"center"];
        }
        [self.view endEditing:YES];
    }];
}

// 重置密码
- (void)userForgetPsw{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *dict = @{@"phone":self.userNameTf.text,
                           @"password":self.passwordTf.text,
                           @"verify_code":self.verificationCodeTf.text
                           };
    
    [JCLoginViewModel userForgetPswParams:dict Success:^(id result) {
        
        if ([result[@"success"] boolValue] == YES) {
            [Tool setObject:self.userNameTf.text forKey:@"ID"];
            [Tool setObject:self.passwordTf.text forKey:@"PSW"];
            [self.view makeToast:@"重置登录密码成功" duration:1 position:@"center"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
               
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.view makeToast:result[@"data"] duration:1 position:@"center"];
        }
        
    }];
    
}


#pragma mark --- 文本框代理
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)refreshVerifyImg:(UIButton *)btn{

    [self getVerifyImgCode];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

